﻿using System;
using System.Text;

namespace CJJ.Common.Validator
{
    /// <summary>
    /// 客户端自定义校验方法
    /// 校验特性需继承 BaseAttribute
    /// </summary>
    public static class CustomValidateExtend
    {
        /// <summary>
        /// 校验
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static string Validate<T>(this T entity) where T : class
        {
            StringBuilder errorMessage = new StringBuilder();
            Type type = entity.GetType();
            foreach (var item in type.GetProperties())
            {
                if (item.IsDefined(typeof(BaseAttribute), true))//此处是重点
                {
                    //此处是重点
                    foreach (BaseAttribute attribute in item.GetCustomAttributes(typeof(BaseAttribute), true))
                    {
                        if (attribute == null)
                        {
                            throw new Exception("AbstractCustomAttribute not instantiate");
                        }

                        bool result = attribute.Validate(item.GetValue(entity), item);
                        if (!result)//校验不通过
                        {
                            errorMessage.Append(attribute.Message);
                            break;//此处为了防止字段被多个校验特性标注，只输出第一个验证不通过的校验信息
                        }
                    }
                }
            }
            return errorMessage.ToString();
        }
    }
}
